import axios from 'axios'
import { ElMessage } from 'element-plus'

// 通用请求配置
const request = axios.create({
  baseURL: '/mock-api',
  timeout: 6000,
})

// 添加一个请求拦截器
request.interceptors.request.use(
  config => {
    // Do something before request is sent
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  },
)

// 添加一个响应拦截器
request.interceptors.response.use(
  response => {
    const { data } = response
    const { code, msg } = data
    if (code === 200) {
      return response.data
    } else if (code === 500) {
      ElMessage.error(`服务器内部错误，请联系管理员进行处理。`)
    } else {
      ElMessage.error(msg)
    }
  },
  error => {
    const { message } = error
    if (message === 'Network Error') {
      ElMessage.error('服务器接口连接异常')
    } else if (message.includes('timeout')) {
      ElMessage.error('服务器接口请求超时')
    } else if (message.includes('Request failed with status code')) {
      ElMessage.error('服务器内部接口 ' + message.substr(message.length - 3) + ' 异常')
    } else {
      return Promise.reject(error)
    }
  },
)

export default request
